package com.fanshuai.spring.boot.local.jdbc;

import com.fanshuai.spring.boot.local.domain.User;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;

@Service
public class NativeTxService {
    @Resource
    private DataSource dataSource1;
    @Resource
    private DataSource dataSource2;

    public boolean batchAdd(List<User> users) {
        if (CollectionUtils.isEmpty(users)) {
            return true;
        }

        boolean b = true;
        Connection connection = null;
        try {
            connection = dataSource1.getConnection();
            connection.setAutoCommit(false);

            for (User user : users) {
                PreparedStatement statement = connection.prepareStatement("insert into user(name) values (?)");
                statement.setString(1, user.getName());

                int affectRows = statement.executeUpdate();
                b = b && affectRows > 0;
            }
            if (b) {
                connection.commit();
            } else {
                connection.rollback();
            }
        } catch (Exception e) {
            if (null != connection) {
                try {
                    connection.rollback();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        } finally {
            if (null != connection) {
                try {
                    connection.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }

        return b;
    }
}
